package com.hmdp.thread;

import cn.hutool.core.io.FileUtil;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

import java.net.URL;

/**
 * @author 陈俊宇
 * @date 2025/9/22
 */
public class Thread2 extends Thread {
    private static final SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);

    private String url; // url
    private String name; // 文件名
    private String downloadPath; // 下载路径

    public Thread2(String url, String name, String downloadPath) {
        this.url = url;
        this.name = name;
        this.downloadPath = downloadPath;
    }

    @Override
    public void run() {
        Downloader downloader = new Downloader();
        try {
            String fileName = generateUniqueFileName(name);
            downloader.download(url, downloadPath + File.separator + fileName);
            System.out.println("下载完成：" + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 使用雪花算法生成唯一文件名
    private String generateUniqueFileName(String originalName) {
        long id = idGenerator.nextId();
        int dotIndex = originalName.lastIndexOf('.');
        if (dotIndex > 0) {
            String name = originalName.substring(0, dotIndex);
            String extension = originalName.substring(dotIndex);
            return name + "_" + id + extension;
        }
        return originalName + "_" + id;
    }

    public static void main(String[] args) {
        String downloadPath = "E:\\imagedownloads"; // 指定下载目录

        for (int i = 0; i < 100; i++) {
            // 不再需要计数器，因为雪花算法会保证唯一性
            Thread2 t1 = new Thread2(
                    "https://ts1.tc.mm.bing.net/th/id/OIP-C.M5yXlRpykxp7K6Nb163C7QHaJI?w=165&h=211&c=8&rs=1&qlt=70&o=7&cb=thws5&dpr=1.1&pid=3.1&rm=3",
                    "image1.png",
                    downloadPath);

            Thread2 t2 = new Thread2(
                    "https://ts1.tc.mm.bing.net/th/id/OIP-C.pIITOdNJEZNos5oKKgMHeQHaHa?w=203&h=211&c=8&rs=1&qlt=70&o=7&cb=thws5&dpr=1.1&pid=3.1&rm=3",
                    "image2.png",
                    downloadPath);

            Thread2 t3 = new Thread2(
                    "https://ts1.tc.mm.bing.net/th/id/OIP-C.afdohncRjxfkMMJQ5jrG_AHaG9?w=217&h=211&c=8&rs=1&qlt=70&o=7&cb=thws5&dpr=1.1&pid=3.1&rm=3",
                    "image3.png",
                    downloadPath);

            t1.start();
            t2.start();
            t3.start();
        }
    }
}

// 下载器
class Downloader {
    // 下载方法
    public void download(String url, String name) throws IOException {
        FileUtils.copyURLToFile(new URL(url), new File(name));
    }
}